import { defineStore } from "pinia";
import { store } from "../index";
import { login, getUserInfo } from "@/api/user";
import type { UserInfo, UserLoginType, UserTokenModel } from "@/api/user/types";
import router from "@/router";
import { SUCCESS_CODE } from "@/axios/constants";

interface UserState {
  // 用户信息
  userInfo?: UserInfo;
  // 登录秘钥
  token: string;
}

export const useUserStore = defineStore("user", {
  state: (): UserState => {
    return {
      userInfo: undefined,
      token: "",
    };
  },
  getters: {
    getToken(): string {
      return this.token;
    },
    getUserInfo(): UserInfo | undefined {
      return this.userInfo;
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setUserInfo(userInfo?: UserInfo) {
      this.userInfo = userInfo;
    },
    login(data: UserLoginType) {
      return new Promise((resolve, reject) => {
        login(data).then((res: IResponse<UserTokenModel>) => {
          if (res.code == SUCCESS_CODE) {
            this.setToken((res.data as UserTokenModel).token);
            resolve(res.data);
          } else {
            reject(res.message);
          }
        });
      });
    },
    getUserInfoByToken() {
      return new Promise((resolve, reject) => {
        getUserInfo().then((res: IResponse<UserInfo>) => {
          if (res.code == SUCCESS_CODE) {
            this.setUserInfo(res.data);
            resolve(res.data);
          } else {
            reject(res.message);
          }
        });
      });
    },
    // 重置数据接口
    reset() {
      this.setToken("");
      this.setUserInfo(undefined);
      router.replace("/login");
    },
    logout() {
      this.reset();
    },
  },
  // 是否持久化数据
  persist: true,
});

export const useUserStoreWithOut = () => {
  return useUserStore(store);
};
